﻿//Copyright (c) 2008 Michael J. Ryan & Apollo Group, Inc.

//Permission is hereby granted, free of charge, to any person
//obtaining a copy of this software and associated documentation
//files (the "Software"), to deal in the Software without
//restriction, including without limitation the rights to use,
//copy, modify, merge, publish, distribute, sublicense, and/or sell
//copies of the Software, and to permit persons to whom the
//Software is furnished to do so, subject to the following
//conditions:

//The above copyright notice and this permission notice shall be
//included in all copies or substantial portions of the Software.

//THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
//EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES
//OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
//NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT
//HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,
//WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
//FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR
//OTHER DEALINGS IN THE SOFTWARE.

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Xml;
using System.Xml.Linq;
using System.IO;

namespace Apollo.Common.Configuration
{
	public class ConfigurationSet
	{
#region Private Variables
		private readonly object _hnd = new object();
		private XDocument _doc;
		private Dictionary<string, ConfigurationItem> _items = new Dictionary<string,ConfigurationItem>();
#endregion
	
#region Constructors
		private ConfigurationSet() {}
		private ConfigurationSet(XDocument doc) {
			_doc = doc;
		}
#endregion

#region Public Static Methods
		public static ConfigurationSet LoadConfig(string xml) {
			//TODO: convert string to memorystream, and create XDocument for constructor.
			MemoryStream ms = new MemoryStream(UTF8Encoding.UTF8.GetBytes(xml));
			XmlReader r = XmlReader.Create(ms);
			XDocument xd = XDocument.Load(r);
			return new ConfigurationSet(xd);
		}
		public static ConfigurationSet Empty
		{
			get { return new ConfigurationSet(); }
		}
#endregion

#region Public Properties
		public ConfigurationItem this[string key] {
			get {
				return GetItem(key);
			}
		}
#endregion

#region Public Methods
		public ConfigurationItem GetItem(string itemName)
		{
			LazyLoad();
			try {
				ConfigurationItem value;
				
				if (_items.TryGetValue(itemName.Trim().ToLower(), out value))
					return value;
				
				return new ConfigurationItem(); //empty item, default
				
			} catch(Exception) {
				return new ConfigurationItem();
			}
		}
#endregion

#region Private Methods
		private void LazyLoad()
		{
			if (_doc == null)
				return; //nothing to load
				
			lock(_items) {
				if (_items.Count > 0)
					return; //already loaded
					
				var elems = from elem in _doc.Descendants("item")
							where elem.Attribute("name") != null
							select elem;
				
				ConfigurationItem item;
				Dictionary<string, ConfigurationItem> items = new Dictionary<string,ConfigurationItem>();
				
				foreach (XElement elem in elems) {
					try
					{
						item = new ConfigurationItem(elem);
						if (items.ContainsKey(item.Name))
							items[item.Name] = item;
						else
							items.Add(item.Name, item);
					}
					catch (Exception ex)
					{
						LogTool.Logger.ErrorException("Apollo...ConfigurationSet.LazyLoad() Raised an exception reading the items.", ex);
						throw;
					}
				}
				
				_items = items; //assign class level var.
				
			}
		}


#endregion

	}
}
